/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.user.rest;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.api.YshopException;
import co.yixiang.logging.aop.log.Log;
import co.yixiang.modules.aop.ForbidSubmit;
import co.yixiang.modules.pay.AppPayService;
import co.yixiang.modules.user.domain.*;
import co.yixiang.modules.user.service.YxUserAddressService;
import co.yixiang.modules.user.service.YxUserBankService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.YxUserinfoService;
import co.yixiang.modules.user.service.dto.UserMoneyDto;
import co.yixiang.modules.user.service.dto.YxUserQueryCriteria;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
* @author hupeng
* @date 2019-10-06
*/
@Api(tags = "商城:会员管理")
@RestController
@RequestMapping("api")
public class MemberController {

    private final YxUserService yxUserService;
    private final AppPayService appPayService;
    private final YxUserAddressService userAddressService;
    private final YxUserinfoService userinfoService;
    private final YxUserBankService userBankService;

    public MemberController(YxUserService yxUserService,AppPayService appPayService , YxUserAddressService userAddressService,
            YxUserinfoService userinfoService , YxUserBankService userBankService) {
        this.yxUserService = yxUserService;
        this.appPayService = appPayService;
        this.userAddressService = userAddressService;
        this.userinfoService = userinfoService;
        this.userBankService = userBankService;
    }

    @Log("查看下级")
    @ApiOperation(value = "查看下级")
    @PostMapping(value = "/yxUser/spread")
    @PreAuthorize("hasAnyRole('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity getSpread(@RequestBody YxUserQueryCriteria criteria){
        return new ResponseEntity<>(yxUserService.querySpread(criteria.getUid(),criteria.getGrade()),
                HttpStatus.OK);
    }
    @Log("查看上级")
    @ApiOperation(value = "查看上级")
    @PostMapping(value = "/yxUser/pSpread")
    @PreAuthorize("hasAnyRole('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity pSpread(@RequestBody YxUserQueryCriteria criteria){
        return new ResponseEntity<>(yxUserService.pSpread(criteria.getUid()),
                HttpStatus.OK);
    }


    @Log("查询直属用户")
    @ApiOperation(value = "查询直属用户")
    @GetMapping(value = "/yxUser/zsUser")
    public ResponseEntity zsUser(@RequestParam(value = "type" , defaultValue = "1") Integer type){
        return new ResponseEntity<>(yxUserService.zsUser(type),HttpStatus.OK);
    }



    @Log("查询开通会员的用户")
    @ApiOperation(value = "查询开通会员的用户")
    @GetMapping(value = "/yxUser/getOpenUserData")
    public ResponseEntity getOpenUserData(){
        return new ResponseEntity<>(yxUserService.getOpenUserData(),HttpStatus.OK);
    }

    @Log("审核")
    @ApiOperation(value = "审核")
    @GetMapping(value = "/yxUser/auditSuccess")
    public ResponseEntity auditSuccess(@RequestParam(value = "orderNo") String orderNo ){

//        yxUserService.auditSuccess(id);
        appPayService.openMemberSuccess(orderNo , "1");

        return new ResponseEntity<>(HttpStatus.OK);
    }


    @Log("查询用户")
    @ApiOperation(value = "查询用户")
    @GetMapping(value = "/yxUser")
    @PreAuthorize("hasAnyRole('admin','YXUSER_ALL','YXUSER_SELECT')")
    public ResponseEntity getYxUsers(YxUserQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(yxUserService.queryAll(criteria,pageable),HttpStatus.OK);
    }


    @Log("修改用户")
    @ApiOperation(value = "修改用户")
    @PutMapping(value = "/yxUser")
    @PreAuthorize("hasAnyRole('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity update(@Validated @RequestBody YxUser resources){
        if(resources.getAfterTime()<0){
            throw new YshopException("提前进场时间须大于0");
        }
        int count = yxUserService.count(new QueryWrapper<YxUser>().lambda()
                .ne(YxUser::getUid, resources.getUid())
                .eq(YxUser::getPhone, resources.getPhone()));
        if (count != 0) throw new YshopException("当前手机号已经存在");
        resources.setUsername(resources.getPhone());
        yxUserService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }


    @Log("修改用户地址")
    @ApiOperation(value = "修改用户地址")
    @PostMapping(value = "/editAddressInfo")
    public ResponseEntity editAddressInfo(@RequestBody YxUserAddress userAddress){
        userAddressService.updateById(userAddress);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }


    @Log("修改用户支付")
    @ApiOperation(value = "修改用户支付")
    @PostMapping(value = "/editPayInfo")
    public ResponseEntity editPayInfo(@RequestBody ZFDateParam zfDateParam){
        YxUserinfo userInfo = userinfoService.getOne(new QueryWrapper<YxUserinfo>().lambda()
                .eq(YxUserinfo::getUid, zfDateParam.getUid()));
        if (zfDateParam.getType() == 1){
            userInfo.setWeixinName(zfDateParam.getName());
            userInfo.setWeixinCode(zfDateParam.getImage());
            if (ObjectUtil.isNotEmpty(zfDateParam.getImage())) userInfo.setWeixinAccount(zfDateParam.getAccount());
            userinfoService.updateById(userInfo);
        }else if (zfDateParam.getType() == 2){
            userInfo.setZhifubaoName(zfDateParam.getName());
            userInfo.setZhifubaoCode(zfDateParam.getImage());
            if (ObjectUtil.isNotEmpty(zfDateParam.getImage())) userInfo.setZhifubaoAccount(zfDateParam.getAccount());
            userinfoService.updateById(userInfo);
        }else if (zfDateParam.getType() == 3){
            YxUserBank userBank = userBankService.getOne(new QueryWrapper<YxUserBank>().lambda()
                    .eq(YxUserBank::getUid, zfDateParam.getUid()));
            userBank.setBankName(zfDateParam.getName());
            userBank.setBankNumber(zfDateParam.getAccount());
            userBank.setImage(zfDateParam.getImage());
            userBank.setRealName(zfDateParam.getRealName());
            userBankService.updateById(userBank);
        }
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }



    @ForbidSubmit
    @Log("删除用户")
    @ApiOperation(value = "删除用户")
    @DeleteMapping(value = "/yxUser/{uid}")
    @PreAuthorize("hasAnyRole('admin','YXUSER_ALL','YXUSER_DELETE')")
    public ResponseEntity delete(@PathVariable Integer uid){
        yxUserService.removeById(uid);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ForbidSubmit
    @ApiOperation(value = "用户禁用启用")
    @PostMapping(value = "/yxUser/onStatus/{id}")
    public ResponseEntity onStatus(@PathVariable Long id,@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Integer status = jsonObject.getInteger("status");
        yxUserService.onStatus(id,status);
        return new ResponseEntity(HttpStatus.OK);
    }


    @ForbidSubmit
    @ApiOperation(value = "用户禁用启用")
    @PostMapping(value = "/yxUser/onStatus1/{id}")
    public ResponseEntity onStatus1(@PathVariable Long id,@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Integer isFreeze = jsonObject.getInteger("isFreeze");
        yxUserService.onStatus1(id,isFreeze);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "修改余额")
    @PostMapping(value = "/yxUser/money")
    @PreAuthorize("hasAnyRole('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity updatePrice(@Validated @RequestBody UserMoneyDto param){
        yxUserService.updateMoney(param);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @ApiOperation(value = "修改积分")
    @PostMapping(value = "/yxUser/integral")
    @PreAuthorize("hasAnyRole('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity updatenItegral(@Validated @RequestBody UserMoneyDto param){
        yxUserService.updatenItegral(param);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @ApiOperation(value = "获取支付信息")
    @GetMapping(value = "/yxUser/getZfData")
    public ResponseEntity getZfData(@RequestParam(value = "uid") Long uid){
        return new ResponseEntity(yxUserService.getZfData(uid) , HttpStatus.OK);
    }


    @ApiOperation(value = "获取收货信息")
    @GetMapping(value = "/yxUser/getShData")
    public ResponseEntity getShData(@RequestParam(value = "uid") Long uid){
        return new ResponseEntity(yxUserService.getShData(uid) , HttpStatus.OK);
    }


    @ApiOperation(value = "删除用户")
    @GetMapping(value = "/yxUser/deleteUser")
    public ResponseEntity deleteUser(@RequestParam(value = "uid") Long uid){
        yxUserService.deleteUser(uid);
        return new ResponseEntity(HttpStatus.OK);
    }

}
